package com.dong8.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.dong8.R;
import com.dong8.resp.CityList;
import com.dong8.resp.CityModel;
import com.dong8.util.PreferencesUtils;
import com.dong8.util.ResourceUtils;
import com.dong8.util.TLog;
import com.dong8.util.Utils;
import com.dong8.widget.MyLetterListView;
import com.dong8.widget.MyLetterListView.OnTouchingLetterChangedListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MyCityListActivity extends Activity {
	private BaseAdapter adapter;
	private ListView mCityLit;
	private TextView overlay;
	private MyLetterListView letterListView;
	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private String[] sections;// 存放存在的汉语拼音首字母
	private Handler handler;
	private OverlayThread overlayThread;
	private SQLiteDatabase database;
	private List<CityModel> mCityNames;

	CityList cList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_list);
		
		findViewById(R.id.ibBack).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				finish();
			}
		});
		((TextView)findViewById(R.id.tv_title)).setText("选择城市");

		mCityLit = (ListView) findViewById(R.id.city_list);
		mCityLit.setOnItemClickListener(new CityListOnItemClick());
		letterListView = (MyLetterListView) findViewById(R.id.cityLetterListView);
		letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
		alphaIndexer = new HashMap<String, Integer>();
		handler = new Handler();
		overlayThread = new OverlayThread();
		initOverlay();

		mCityNames = getCityList();
		setAdapter(mCityNames);

	}

	private List<CityModel> getCityList() {
		List<CityModel> names = new ArrayList<CityModel>();

		getData();

		if (cList != null) {
			names = cList.toModelList();
		}

		return names;
	}

	public void getData() {
		cList = Utils.getCityList(MyCityListActivity.this);
		if (cList == null) {

			String json = ResourceUtils.geFileFromRaw(MyCityListActivity.this, R.raw.city);
			cList = JSON.parseObject(json, CityList.class);
			PreferencesUtils.putString(MyCityListActivity.this, "CITY_LIST", json);

		}

	}

	@SuppressWarnings("unused")
	private ArrayList<CityModel> getCityNames() {
		ArrayList<CityModel> names = new ArrayList<CityModel>();
		Cursor cursor = database.rawQuery("SELECT * FROM T_City ORDER BY NameSort", null);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			CityModel cityModel = new CityModel();
			cityModel.cityName = cursor.getString(cursor.getColumnIndex("CityName"));
			cityModel.nameSort = cursor.getString(cursor.getColumnIndex("NameSort"));
			names.add(cityModel);
		}
		return names;
	}

	class CityListOnItemClick implements OnItemClickListener 
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) 
		{
			CityModel cityModel = (CityModel) mCityLit.getAdapter().getItem(pos);
			PreferencesUtils.putString(MyCityListActivity.this, "city",
					cityModel.cityCode + "-" + cityModel.cityName);
			
			Intent aintent = new Intent(MyCityListActivity.this, RecommendGymActivity.class);
			aintent.putExtra("code", cityModel.cityCode);
			setResult(100,aintent); 
			finish();
		}
	}

	private void setAdapter(List<CityModel> list) {
		if (list != null) {
			adapter = new ListAdapter(this, list);
			mCityLit.setAdapter(adapter);
		}

	}

	/**
	 * ListViewAdapter
	 * 
	 * @author sy
	 * 
	 */
	private class ListAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private List<CityModel> list;

		public ListAdapter(Context context, List<CityModel> list) {

			this.inflater = LayoutInflater.from(context);
			this.list = list;
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];

			for (int i = 0; i < list.size(); i++) {

				String currentStr = list.get(i).nameSort;
				TLog.i("hansen", "===currentStr=::" + currentStr);
				// 上一个汉语拼音首字母，如果不存在为“ ”
				String previewStr = (i - 1) >= 0 ? list.get(i - 1).nameSort : " ";
				if (!previewStr.equals(currentStr)) {
					String name = list.get(i).nameSort;
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}

		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_city, null);
				holder = new ViewHolder();
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.name.setText(list.get(position).cityName);
			String currentStr = list.get(position).nameSort;
			String previewStr = (position - 1) >= 0 ? list.get(position - 1).nameSort : " ";
			if (!previewStr.equals(currentStr)) {
				holder.alpha.setVisibility(View.VISIBLE);
				holder.alpha.setText(currentStr);
			} else {
				holder.alpha.setVisibility(View.GONE);
			}
			return convertView;
		}

		private class ViewHolder {
			TextView alpha;
			TextView name;
		}

	}

	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private class LetterListViewListener implements OnTouchingLetterChangedListener {
		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);
				mCityLit.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.VISIBLE);
				handler.removeCallbacks(overlayThread);
				handler.postDelayed(overlayThread, 1500);
			}
		}

	}

	private class OverlayThread implements Runnable {

		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

}